<template>
  <layout-card
    v-model="search"
    :filters="exampleOptions"
    headline="信息列表"
    headtitle="信息列表"
    :hasButton="true"
    @search-change="pageInfo"
    @search-reset="searchReset">
    <template #action>
      <el-button
          type="primary"
          @click="addClass"
      >新增</el-button>
    </template>
    <table-common
      stripe="true"
      :columns="exampleColumns"
      :loading="loading"
      :pagination="pager"
      :table-data="list"
      size="large"
      @current-change="changeCurrent"
      @size-change="changePageSize"
      @sort-change="sortChange">
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button
            class="link-btn"
            link
            type="primary"
        @click="editClass(row)">编辑</el-button>
        <el-popconfirm
            title="是否删除?"
            confirmButtonText="确定"
            cancelButtonText="取消"
            @confirm="() => deletepeoFn(row)"
        >
          <template #reference>
            <el-button
                class="link-btn"
                link
                type="danger"
            >删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>
  <!-- 新增/编辑分组弹窗   -->
  <edit-dialog
    class="maintenance"
    :centerDialogVisible="addGroupDialogVisible"
    :tilte="addGroupTitle"
    :key="timer"
    align-center
    :defaultButton="false"
    :width="500"
    @cancel="handleCancel"
  >
    <template #content>
      <el-form :model="ruleForm" :rules="rules" ref="goodsTypeFormRef">
        <el-form-item label-width="80px" label="班次名称" prop="className">
          <el-input v-model="ruleForm.className" />
        </el-form-item>
        <el-form-item label-width="80px" label="班次类型" prop="classType">
          <el-radio-group v-model="ruleForm.classType" :disabled="addGroupTitle=='编辑班次'?true:false">
            <el-radio v-for="item in fileTypes"
                      :key="item.id" :label="item.value">
              {{item.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label-width="80px" label="起始时间" prop="date" v-if="ruleForm.classType=='S'">
          <el-time-picker
              v-model="ruleForm.date"
              is-range
              range-separator="-"
              start-placeholder="hh:mm"
              end-placeholder="hh:mm"
              value-format="HH:mm"
              format="HH:mm"
          />
        </el-form-item>

      <el-form-item v-if="ruleForm.classType=='F'">
        <el-table ref="tableRef" :data="dataList" style="min-width: 100%;" border >
          <el-table-column prop="dayText"  label="工作日"  width="80"/>
          <el-table-column prop="content" label="时间" header-align="center">
            <template #default="scope">
              <el-form-item :rules="rules.date1">
                <el-time-picker
                    v-model="scope.row.dateStr"
                    is-range
                    range-separator="-"
                    start-placeholder="hh:mm"
                    end-placeholder="hh:mm"
                    value-format="HH:mm"
                    format="HH:mm"
                />
              </el-form-item>

            </template>
          </el-table-column>
        </el-table>

      </el-form-item>

       <el-form-item label-width="80px" label="连续上班" prop="workDay" v-if="ruleForm.classType=='C'">
          <el-input v-model="ruleForm.workDay" type="number" @input="(e)=>{return  handleEdit(e,0)}">
            <template #append>天</template>
          </el-input>
        </el-form-item>
        <template v-for="(item,index) in ruleForm.dateList">
        <el-form-item label-width="160px" :label="'第'+(index+1)+'天上班时间'"  v-if="ruleForm.classType=='C'"
                      :prop="`dateList[${index}][date]`" :rules="rules.date"
        >
          <el-time-picker
              v-model="item.date"
              is-range
              range-separator="-"
              start-placeholder="hh:mm"
              end-placeholder="hh:mm"
              value-format="HH:mm"
              format="HH:mm"
          />
        </el-form-item>
        </template>
        <el-form-item label-width="80px" label="连续休息" prop="restDay" v-if="ruleForm.classType=='C'">
          <el-input v-model="ruleForm.restDay" type="number" @input="(e)=>{return  handleEdit(e,1)}">
            <template #append>天</template>
          </el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #custom>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="saveBtn" @click="handleTransferSubmit(goodsTypeFormRef)">保存</el-button>
        </span>
    </template>
  </edit-dialog>
</template>
<script lang="ts" setup>
import {ref, reactive, onMounted, computed, onBeforeMount, watch, nextTick, toRaw} from 'vue'
// 7-18修改LayoutCard 页面，hasButton参数为false时显示为弹窗样式，为true时显示为搜索栏样式
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import { exampleColumns } from '@/views/quality/scheduleClass/config/columns'
import { exampleOptions } from '@/views/quality/scheduleClass/config/filters'
import editDialog from '@/components/editDialog/index.vue';
import {ElMessage, FormInstance, FormRules} from 'element-plus'
import {getResource} from "@/api/resource";
import {getScheduleClassList, scheduleClassAdd, scheduleClassDel, scheduleClassEdit} from "@/api/quality/scheduleClass";
import {useStore} from "vuex";
const addGroupDialogVisible = ref(false); // 新增/编辑弹窗是否打开
const addGroupTitle = ref<string>(""); // 新增/编辑弹窗标题
const timer = ref(); // 弹窗时间戳
const store = useStore()
const userInfo = computed(() => store.state.user.userInfo)
const saveBtn = ref(false); // 确认按钮加载动画
const goodsTypeFormRef = ref<FormInstance>()
const fileTypes=ref([])//班次类型
const dataList=ref([])//固定班制
// 新增/编辑 表单验证
const ruleForm = ref({
  className: '',
  classType:"S",
  date:"",//起始时间
  workDay:undefined,
  restDay:undefined,
  dateList:[]

}); // 新增/编辑分组表单
const rules = reactive<FormRules>({
  className: [
    {
      required: true,
      message: '请填写班次名称',
      trigger: 'blur',
    },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  workDay: [
    {
      required: true,
      message: '请输入上班天数',
      trigger: 'blur',
    },
  ],
  restDay: [
    {
      required: true,
      message: '请输入休息天数',
      trigger: 'blur',
    },
  ],
  date: [
    {
      required: true,
      message: '请选择上下班时间',
      trigger: 'blur',
    },
  ],
  date1: [
    {
      required: true,
      message: '请选择上下班时间',
      trigger: 'blur',
    },
  ],
  date2: [
    {
      required: true,
      message: '请选择上下班时间',
      trigger: 'blur',
    },
  ]
})
// 存储获取回来的值
const list = ref([])
const loading = ref(false)
// 分页
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageCount: 1
})
// 排序
const order = ref([
  {
    column: 'create_time',
    method: 'desc'
  }
])
const searchModel=ref({
  className:'',
  classType:''
})
watch(() => ruleForm.value.workDay, (val, oldVal) => {
  ruleForm.value.dateList=[]
  for (let r = 0; r < ruleForm.value.workDay; r++) {
    ruleForm.value.dateList.push({
      date:''
    })
  }

})
const handleEdit=(e,index)=> {
  if(index==0)ruleForm.value.workDay = e.replace(/^(0+)|[^\d]+/g,'')
  if(index==1)ruleForm.value.restDay = e.replace(/^(0+)|[^\d]+/g,'')
}
const changeCurrent = (val: number) => {
  pager.currentPage = val
  getList()
}
// 每页展示条数发生变化
const changePageSize = (val: number) => {
  pager.currentPage = 1;
  pager.pageSize = val;
  //order.value = [];// 清空排序？？？
  getList()
}

const sortChange = (data: any) => {
  const method = data.order === 'ascending' ? 'asc' : 'desc'
  order.value[0].column = 'create_time'
  order.value[0].method = method
  getList()
}

const pageInfo = async (data:any) => {
  console.log(data)
  searchModel.value.className=data.className
  searchModel.value.classType=data.classType
  getList()
}

const searchReset = (data: any) => {
  searchModel.value.className=''
  searchModel.value.classType=''
  getList()
}
const handleCancel = () => {
  addGroupDialogVisible.value = false;
  addGroupTitle.value = "";
  saveBtn.value=false
};
const handleTransferSubmit =async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let fetch = scheduleClassAdd;

      const payload={
        className:ruleForm.value.className,
        classType:ruleForm.value.classType

      };
      if(payload.classType=="S"){
        //排班制
        payload.classDetail=JSON.stringify({
          date:ruleForm.value.date,
          classType:payload.classType
        })
      }else if(payload.classType=='C'){
          //轮班制
        // if(Number(ruleForm.value.workDay)+Number(ruleForm.value.restDay)>7){
        //   ElMessage.success("轮班时长不能大于7天")
        //   saveBtn.value=false
        //   return
        // }
        payload.classDetail=JSON.stringify({
          date:{
            workDay:ruleForm.value.workDay,
           dateList:ruleForm.value.dateList,
            restDay:ruleForm.value.restDay
          },
          classType:payload.classType
        })
      }else{
        //固定班
        let flag=false
        dataList.value.forEach(item=>{
          if(item.dateStr!=''&&item.dateStr!=null)flag=true
        })
        if(!flag){
          ElMessage.info("固定班制至少填充一天的时间")
          return
        }
        payload.classDetail=JSON.stringify({
          classType:payload.classType,
          date:dataList.value
        })
      }
      saveBtn.value=true
      if (addGroupTitle.value == '编辑班次') {
        fetch = scheduleClassEdit;
        payload.mender = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          userName: userInfo.value.userName,
          organId: userInfo.value.organId || '',
          organName: userInfo.value.organName || ''
        }
        payload.id=ruleForm.value.id
      }else{
        payload.creator = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          userName: userInfo.value.userName,
          organId: userInfo.value.organId || '',
          organName: userInfo.value.organName || ''
        }
      }
      const res = await fetch(payload);
      if(res?.code ==='1'){
        if(addGroupTitle.value == '编辑班次'){
          ElMessage.success("编辑成功")
        }else{
          ElMessage.success("新增成功")
        }
        handleCancel();
        getList()
      }else{
        ElMessage.error(res?.message || '操作失败，请重试！');
        saveBtn.value=false
      }


    }
  })
}
const onGetResource= async () => {
  const res = await getResource("tcdm_class_type");
  if(res.code=='1'){
    fileTypes.value=res.data.properties.meta
    exampleOptions.value[1].inputProps.options =fileTypes.value
  }
  getList()
};
const addClass=()=>{
  addGroupDialogVisible.value=true
  addGroupTitle.value="新增班次"
  onRest()
}
const editClass=(row:any)=>{
  onRest()
  addGroupDialogVisible.value=true
  addGroupTitle.value="编辑班次"

  const item=JSON.parse(JSON.stringify(row))
  ruleForm.value.className=item.className
  ruleForm.value.classType=item.classType
  ruleForm.value.id=item.id
  const json=JSON.parse(eval("("+item.classDetail+")"))
  if(item.classType=="S"){
    //排班制
    ruleForm.value.date=json.date

  }else if(item.classType=='C'){
    //轮班制
    ruleForm.value.workDay=json.date.workDay
        ruleForm.value.dateList=json.date.dateList
        ruleForm.value.restDay=json.date.restDay

  }else{
    dataList.value=json.date

  }
}
const onRest=()=>{
  dataList.value=[
    {
      dayText:"周一",
      dateStr:''
    },
    {
      dayText:"周二",
      dateStr:''
    },
    {
      dayText:"周三",
      dateStr:''
    },
    {
      dayText:"周四",
      dateStr:''
    },{
      dayText:"周五",
      dateStr:''
    },{
      dayText:"周六",
      dateStr:''
    },
    {
      dayText:"周日",
      dateStr:''
    }
  ]
  ruleForm.value={
    className: '',
    classType:"S",
    date:"",//起始时间
    workDay:undefined,
    restDay:undefined,
    date1:'',
    date2:''
  }
}
const getList=async () => {
  loading.value = true;
  list.value=[]
  const payload = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {
      ...searchModel.value,
      order:order.value
    }
  }
  //获取表格数据
  const res = await getScheduleClassList(payload);
  if (res?.code == '1') {
    list.value = res.data.list;
    pager.total = res.data.total;
    pager.pageCount =
        Math.ceil(pager.total / pager.pageSize) === 0
            ? 1
            : Math.ceil(pager.total / pager.pageSize);
  }
  loading.value = false
}
const deletepeoFn=async (row:any) => {
  const res = await scheduleClassDel(row.id)
  if(res?.code ==='1'){
    ElMessage.success("删除成功")
    getList()
  }else{
    ElMessage.error(res?.message || '操作失败，请重试！');
  }
}
onBeforeMount(() => {
  onGetResource()

})

</script>
